package wangxu

import (
	"fmt"
	"github.com/beherochuling/beesoft_api/app/dao"
	"github.com/beherochuling/beesoft_api/app/helper/net/websocket"
	"github.com/beherochuling/beesoft_api/app/model/entity"
	model "github.com/beherochuling/beesoft_api/app/model/wangxu"
	"github.com/gogf/gf/v2/text/gstr"
)

var LetsviewCallback = letsviewCallbackService{}

type letsviewCallbackService struct{}

func (r *letsviewCallbackService) OnOpen(ws *websocket.Websocket) {
	// ws.FD
	queries, err := gstr.Parse(ws.Request.URL.RawQuery)
	if err != nil {
		panic(err)
	}

	var auth string
	if len(queries) > 0 {
		value, ok := queries["auth"]
		if ok {
			auth = value.(string)
		}
	}

	ctx := ws.Request.Context()
	user := NewLetsviewUser(ctx).GetByAuth(auth)
	if user == nil {
		ws.Write(&websocket.JsonObject{
			Status:  model.MessageTypeNoAuth,
			Message: "authFailed",
			Data:    nil,
		})
		ws.Close()
		return
	}
	// olds := wangxu.NewLetsviewConnection(ctx).GetByCode(user.Code)
	// wangxu.Clear(olds)

	_, err = dao.LetsviewConnections.Ctx(ctx).
		Insert(entity.LetsviewConnections{
			Fd:   ws.FD,
			Code: user.Code,
		})
	if err != nil {
		panic(err)
	}

	ws.Write(&websocket.JsonObject{
		Status:  model.MessageTypeWelcome,
		Message: "welcome",
		Data:    nil,
	})
}
func (r *letsviewCallbackService) OnClose(ws *websocket.Websocket) {
	ctx := ws.Request.Context()

	user := NewLetsviewConnection(ctx).GetByFd(ws.FD)
	if user == nil {
		return
	}
	fmt.Println(user)

	// 	clear fd code

	// 	clear code
	return
}
